package com.agadmin.manage.handle.software;

import com.agadmin.api.Api;
import com.agadmin.entity.software.Software;
import com.agadmin.manage.ManageApiHandle;
import com.agadmin.manage.common.SoftKeyUtils;
import com.agadmin.manage.vo.reponse.software.SoftwareAddResponse;
import com.agadmin.manage.vo.request.software.SoftwareAddRequest;
import com.agadmin.mapper.SoftwareMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Transactional
@Api
public class SoftwareAddManage implements ManageApiHandle<SoftwareAddRequest, SoftwareAddResponse> {

    @Autowired
    SoftwareMapper softwareMapper;

    @Override
    public SoftwareAddResponse handler(SoftwareAddRequest softwareAddRequest) {
        SoftwareAddResponse res = new SoftwareAddResponse();

        boolean addResult = false;

        addResult = addSoftware(softwareAddRequest);

        if (addResult) {
            res.setCode(200);
            res.setMsg("add successful");
        } else {
            res.setCode(402);
            res.setMsg("add fail,duplicate name are found");
        }

        return res;
    }


    private boolean addSoftware(SoftwareAddRequest req) {
        Software software = new Software();

        BeanUtils.copyProperties(req, software, "id");
        software.setUserId(req.getUserId());
        String key = generationSoftKey();
        software.setSoftwareKey(key);

        try {
            int insert = softwareMapper.insert(software);
            return insert > 0;
        } catch (Exception e) {
            return false;
        }

    }

    private String generationSoftKey() {
        String key = SoftKeyUtils.createKey();
        return key;
    }
}
